#include"Graviation.h"
#include"Box2D/Box2D.h"
#include"LSYEasyBody.h"
#include"LSYEasyWorld.h"
#include"GLES-Render.h"
#include"BirdThrower.h"
#include"GrasviationListener.h"
#include"Tool.h"

bool Graviation::init()
{
	if (!AbstractLayer::init(b2Vec2(0,0)))
	{
		return false;
	}
	return true;
}

void Graviation::box2DAppReady()
{
	planet = LSYEasyBody::createCircle(b2Vec2(600, 400), 50, b2BodyType::b2_kinematicBody);
	sensor = LSYEasyBody::createCircle(b2Vec2(600, 400), 170, b2BodyType::b2_kinematicBody);
	sensor->GetFixtureList()->SetSensor(true);

	bird = LSYEasyBody::createBox(b2Vec2(100, 180), b2Vec2(10, 10));
	birdManager = new BirdThrower(this, bird, b2Vec2(100, 250));

	listener = new GrasviationListener(this);
	pWorld->SetContactListener(listener);
}

void Graviation::update(float dt)
{
	AbstractLayer::update(dt);

	if (listener->isBirdSensor)
	{
		b2Vec2 force = planet->GetPosition() - bird->GetPosition();
		force.Normalize();
		force *= bird->GetMass() * 10;
		bird->ApplyForce(force, bird->GetPosition(), true);
		bird->SetLinearDamping(0.2);
	}
}

bool Graviation::onTouchBegan(cocos2d::Touch * touch, cocos2d::Event * unused_event)
{
	birdManager->onMouseDown(b2Vec2(touch->getLocation().x, touch->getLocation().y));
	return true;
}

void Graviation::onTouchEnded(cocos2d::Touch * touch, cocos2d::Event * unused_event)
{
	birdManager->onMouseUp(b2Vec2(touch->getLocation().x, touch->getLocation().y));
}

void Graviation::onTouchMoved(cocos2d::Touch * touch, cocos2d::Event * unused_event)
{
	birdManager->onMouseMove(b2Vec2(touch->getLocation().x, touch->getLocation().y));
}

void Graviation::onExit()
{
	AbstractLayer::onExit();
	REALSE_NULL(birdManager);
}
